package jtt809;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.sjx.util.MockUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import jtt809.handler.initializer.ClientJtt809Initializer;
import jtt809.pojo.RequestClientJtt809_0x1001;
import jtt809.pojo.RequestJtt809_0x1200_VehicleColor;
import jtt809.pojo.RequestJtt809_0x1202;
import jtt809.pojo.ResponseClientJtt809_0x1002;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * 主链路
 * 下级平台客户端
 */
public class PrimaryLinkClientManager implements Runnable {
    private static final Log logger = LogFactory.get();

    private Bootstrap bootstrap;

    private Channel channel;

    private String ip;

    private int port;

    private String downLinkIp;

    private int downLinkPort;

    public PrimaryLinkClientManager(String ip, int port, String downLinkIp, int downLinkPort) {
        this.ip = ip;
        this.port = port;
        this.downLinkIp = downLinkIp;
        this.downLinkPort = downLinkPort;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getDownLinkIp() {
        return downLinkIp;
    }

    public void setDownLinkIp(String downLinkIp) {
        this.downLinkIp = downLinkIp;
    }

    public int getDownLinkPort() {
        return downLinkPort;
    }

    public void setDownLinkPort(int downLinkPort) {
        this.downLinkPort = downLinkPort;
    }

    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientJtt809Initializer(ip, port, downLinkIp, downLinkPort));

            // 连接服务端
            ChannelFuture channelFuture = bootstrap.connect(ip, port);
            channelFuture.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        final EventLoop loop = future.channel().eventLoop();
                        loop.schedule(new Runnable() {
                            public void run() {
                                logger.info("======> 上级平台连接不上，开始重连操作......");
                                start();
                            }
                        }, 5L, TimeUnit.SECONDS);
                    } else {
                        channel = future.channel();
                        logger.info("======> 上级平台连接成功......");
                    }
                }
            });

            Thread.sleep(5000);

            // 发送登录指令
            RequestClientJtt809_0x1001 jtt8090X1001Client = new RequestClientJtt809_0x1001();
            jtt8090X1001Client.setEncryptFlag((short) 0);
            jtt8090X1001Client.setEncryptKey(10);

            jtt8090X1001Client.setUserId(13579);
            jtt8090X1001Client.setPassword("Hf1234");
            jtt8090X1001Client.setDownLinkIp(this.downLinkIp);
            jtt8090X1001Client.setDownLinkPort(this.downLinkPort);
            channel.writeAndFlush(jtt8090X1001Client.encode());

            Thread.sleep(3000);

            if (ResponseClientJtt809_0x1002.isIsLoginFlagFromUpPlatform()) {

                while (true) {
                    // 等待[0,5000)毫秒
                    Thread.sleep(RandomUtil.randomInt(2000, 5000));

                    RequestJtt809_0x1202 requestJtt8090x1202 = new RequestJtt809_0x1202();
                    requestJtt8090x1202.setVehicleNo(MockUtil.getVechileNo());
                    requestJtt8090x1202.setVehicleColor(RequestJtt809_0x1200_VehicleColor.BLUE);
                    requestJtt8090x1202.setEncrypt((byte) 0);
                    requestJtt8090x1202.setDateTime(Calendar.getInstance());

                    requestJtt8090x1202.setLon(MockUtil.randomLonLat(117.5675674618, 117.6984245470, 24.9297423670, 25.0475137438, "lon"));
                    requestJtt8090x1202.setLat(MockUtil.randomLonLat(117.5675674618, 117.6984245470, 24.9297423670, 25.0475137438, "lat"));
                    requestJtt8090x1202.setVec1((short) RandomUtil.randomInt(150));
                    requestJtt8090x1202.setVec2((short) RandomUtil.randomInt(150));
                    requestJtt8090x1202.setVec3((short) RandomUtil.randomInt(10000));
                    requestJtt8090x1202.setDirection((short) RandomUtil.randomInt(0, 360));
                    requestJtt8090x1202.setAltitude((short) RandomUtil.randomInt(0, 6000));

                    channel.writeAndFlush(requestJtt8090x1202);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        start();
    }
}
